const BaseRest = require('./rest.js');
const { think } = require('thinkjs');

module.exports = class extends BaseRest {
  constructor(ctx) {
    super(ctx);
    this.usersService = think.service('users');
    this.tokenService = think.service('token');
  }

  /**
   * 获取令牌
   */
  async getAction() {
    // 获取账号、密码参数
    const account = this.header('account');
    const password = this.header('password');

    // 判断账号、密码是否匹配
    const id = await this.usersService.isByAccountAndPassword(
      account,
      password
    );
    if (id === -1) {
      this.status = 404;
      return (this.body = {
        error: '用户不存在',
        message: '请先创建用户'
      });
    }
    if (id === -2) {
      this.status = 401;
      return (this.body = {
        error: '密码错误',
        message: '请输入正确的密码'
      });
    }

    // // 签发令牌
    const token = this.tokenService.sign({ id });
    this.body = { token };
  }
};
